package com.fushenlan.epidemicControl.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fushenlan.commons.ApiGlobalErrorDefinition;
import com.fushenlan.commons.GeneralResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @author Administrator
 * @date 2022/5/2 11:24
 */
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    private JwtProvider jwtProvider;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("options".equalsIgnoreCase(request.getMethod())) {
            log.info("options  method access");
            return true;
        }
        String token = jwtProvider.resolveToken(request);
        if (StrUtil.isBlank(token)) {
            log.info("token empty");
            doResponse(response, GeneralResponse.fail(ApiGlobalErrorDefinition.TOKEN_EMPTY));
            return false;
        }
        String openid = JWTUtil.parseToken(token).getPayload("openid").toString();
        log.info("token payload openid :{}", openid);
        if (!jwtProvider.validateToken(token, openid)) {
            log.info("invalid token");
            doResponse(response, GeneralResponse.fail(ApiGlobalErrorDefinition.TOKEN_INVALID));
            return false;
        }
        //查询这个token有没有在黑名单中
        Object claim = JWTUtil.parseToken(token).getPayload().getClaim(JWTPayload.JWT_ID);
        String access_token = redisTemplate.opsForValue().get("thirdSession-black-list:" + claim);
        if (StrUtil.isNotBlank(access_token)) {
            log.info("invalid token cause token in black list");
            doResponse(response, GeneralResponse.fail(ApiGlobalErrorDefinition.TOKEN_INVALID, "token in black list"));
            return false;
        }
        if (jwtProvider.isNeedUpdate(token)) {
            log.info("refresh token");
            String refreshToken = jwtProvider.refreshToken(token, new HashMap<>(), openid);
            response.setHeader(jwtProperties.getHeader(), refreshToken);
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    private void doResponse(HttpServletResponse response, GeneralResponse resultVO) throws IOException {

        response.setContentType("application/json");

        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        String s = new ObjectMapper().writeValueAsString(resultVO);

        out.print(s);

        out.flush();

        out.close();

    }

}

